<?php function ToAsc($str,$encode='utf-8'){
	$str = iconv($encode, "UTF-16BE", $str);
	for($i=0;$i<strlen($str); $i++,$i++){
		$code = ord($str{$i}) * 256 + ord($str{$i + 1});
		if($code<128){
			$output .= chr($code);
		}elseif($code!=65279) {
			$output.="&#".$code.";";
		}
	}
	return $output;
}
function readover($filename,$method="rb"){
	if($handle=@fopen($filename,$method)){
		flock($handle,LOCK_SH);
		$filedata=fread($handle,filesize($filename));
		fclose($handle);
	}
	return $filedata;
}
function writeover($filename,$data,$method="rb+",$iflock=1){
	touch($filename);
	$handle=fopen($filename,$method);
	if($iflock){
		flock($handle,LOCK_EX);
	}
	fwrite($handle,$data);
	if($method=="rb+") ftruncate($handle,strlen($data));
	fclose($handle);
}
function mkdirs($dir){
  if(!is_dir($dir)){
    mkdirs(dirname($dir));
    mkdir($dir,0777);
  }
  return ;
}
function _sizecount($filesize) {
  if($filesize >= 1073741824) {
    $filesize = round($filesize / 1073741824 * 100) / 100 . ' GB';
  } elseif($filesize >= 1048576) {
    $filesize = round($filesize / 1048576 * 100) / 100 . ' MB';
  } elseif($filesize >= 1024) {
    $filesize = round($filesize / 1024 * 100) / 100 . ' KB';
  } else {
    $filesize = $filesize . ' Bytes';
  }
  return $filesize;
}
function oiconv($from,$to,$string){
  if(function_exists('mb_convert_encoding')){
    return mb_convert_encoding($string,$to,$from);
  }else{
    return iconv($from,$to,$string);
  }
}
function StrCode($string,$action='ENCODE'){
	$action != 'ENCODE' && $string = base64_decode($string);
	$code = '';
	$key  = substr(md5(KEY),8,18);
	$keylen = strlen($key); $strlen = strlen($string);
	for ($i=0;$i<$strlen;$i++) {
		$k		= $i % $keylen;
		$code  .= $string[$i] ^ $key[$k];
	}
	return ($action!='DECODE' ? base64_encode($code) : $code);
}

function _cookie($var, $value = null, $life = 0, $prefix = 1, $httponly = false) {
	global $cookiepre, $cookiedomain, $cookiepath, $timestamp, $_SERVER;
	$timestamp=time();
	$var = ($prefix ? $cookiepre : '').$var;
	if($value===null){
    return $_COOKIE[$var];
	}
	if($value == 'del' || $life < 0) {
		$value = '';
		$life = -1;
	}
	$cookiepath='/';
	$life = $life > 0 ? $timestamp + $life : ($life < 0 ? $timestamp - 31536000 : 0);
	$path = $httponly && PHP_VERSION < '5.2.0' ? "$cookiepath; HttpOnly" : $cookiepath;
	$secure = $_SERVER['SERVER_PORT'] == 443 ? 1 : 0;
	if(PHP_VERSION < '5.2.0') {
		setcookie($var, $value, $life, $path, $cookiedomain, $secure);
	} else {
		setcookie($var, $value, $life, $path, $cookiedomain, $secure, $httponly);
	}
  $GLOBALS['C'].='<br />'.$var.': '.$value.', '.date('Y-m-d H:i:s',$life);
}
function InitGP($keys,$method=null,$cvtype=1){//0=null,1=Char_cv,2=int
	!is_array($keys) && $keys = array($keys);
	foreach ($keys as $key) {
		if ($key == 'GLOBALS') continue;
		$GLOBALS[$key] = NULL;
		if ($method != 'P' && isset($_GET[$key])) {
			$GLOBALS[$key] = $_GET[$key];
		} elseif ($method != 'G' && isset($_POST[$key])) {
			$GLOBALS[$key] = $_POST[$key];
		}
		if (isset($GLOBALS[$key]) && !empty($cvtype) || $cvtype==2) {
			$GLOBALS[$key] = Char_cv($GLOBALS[$key],$cvtype==2,true);
		}
	}
}
function GP($keys,$method=null,$cvtype=1){
	if($method=='G'){
		$value=$_GET[$keys];
	}elseif($method=='P'){
		$value=$_POST[$keys];
	}else{
		$value=$_REQUEST[$keys];
	}
	if (!empty($cvtype) || $cvtype==2) {
		$value = Char_cv($value,$cvtype==2,true);
	}
	return $value;
}
function Char_cv($mixed,$isint=false,$istrim=false) {
	if (is_array($mixed)) {
		foreach ($mixed as $key => $value) {
			$mixed[$key] = Char_cv($value,$isint,$istrim);
		}
	} elseif ($isint) {
		$mixed = (int)$mixed;
	} elseif (!is_numeric($mixed) && ($istrim ? $mixed = trim($mixed) : $mixed) && $mixed) {
		$mixed = str_replace(array("\0","%00","\r"),'',$mixed);
		$mixed = preg_replace(
			array('/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F]/','/&(?!(#[0-9]+|[a-z]+);)/is'),
			array('','&amp;'),
			$mixed
		);
		$mixed = str_replace(array("%3C",'<'),'&lt;',$mixed);
		$mixed = str_replace(array("%3E",'>'),'&gt;',$mixed);
		$mixed = str_replace(array('"',"'","\t",'  '),array('&quot;','&#39;','    ','&nbsp;&nbsp;'),$mixed);
	}
	return $mixed;
}

function ostripslashes($string, $force = 0) {
  if(is_array($string)) {
    foreach($string as $key => $val) {
      $string[$key] = ostripslashes($val, $force);
    }
  } else {
    $string = stripslashes($string);
  }
	return $string;
}
function onez_json($a=false){
  if (is_null($a)) return 'null'; 
  if ($a === false) return 'false'; 
  if ($a === true) return 'true'; 
  if (is_scalar($a)){ 
    if (is_float($a)){ 
      return floatval(str_replace(",", ".", strval($a))); 
    } 
    if (is_string($a)) { 
      static $jsonReplaces = array(array("\\", "/", "\n", "\t", "\r", "\b", "\f", '"'), array('\\\\', '\\/', '\\n', '\\t', '\\r', '\\b', '\\f', '\"')); 
      return '"' . str_replace($jsonReplaces[0], $jsonReplaces[1], $a) . '"'; 
    }else{
       return $a; 
    }
  } 
  $isList = true; 
  for($i = 0, reset($a); $i < count($a); $i++, next($a)){ 
    if(key($a) !== $i){ 
      $isList = false; 
      break; 
    } 
  } 
  $result = array(); 
  if ($isList){ 
    foreach ($a as $v) $result[] = onez_json($v); 
    return '[' . join(',', $result) . ']'; 
  }else{
    foreach ($a as $k => $v) $result[] = onez_json($k).':'.onez_json($v); 
    return '{' . join(',', $result) . '}'; 
  } 
}

function osubstr($str, $start=0, $length, $charset="utf-8", $suffix=true){
  if(function_exists("mb_substr")){
    if(mb_strlen($str, $charset) <= $length) return $str;
    $slice = mb_substr($str, $start, $length, $charset);
  }else{
    $re['utf-8']  = "/[\x01-\x7f]|[\xc2-\xdf][\x80-\xbf]|[\xe0-\xef][\x80-\xbf]{2}|[\xf0-\xff][\x80-\xbf]{3}/";
    $re['gb2312'] = "/[\x01-\x7f]|[\xb0-\xf7][\xa0-\xfe]/";
    $re['gbk&']     = "/[\x01-\x7f]|[\x81-\xfe][\x40-\xfe]/";
    $re['big5']     = "/[\x01-\x7f]|[\x81-\xfe]([\x40-\x7e]|\xa1-\xfe])/";
    preg_match_all($re[$charset], $str, $match);
    if(count($match[0]) <= $length) return $str;
    $slice = join("",array_slice($match[0], $start, $length));
  }
  if($suffix) return $slice."…";
  return $slice;
}
function ostrlen($string = null) {
  preg_match_all("/[0-9]{1}/",$string,$arrNum);  
  preg_match_all("/[a-zA-Z]{1}/",$string,$arrAl);  
  preg_match_all("/./us",$string,$arrCh); 
  return count($arrNum[0]+$arrAl[0]+$arrCh[0]);
}

/**
 * 连接数据库,需在config.inc.php设置对应的连接信息
 * @param $token
 */
function D($token='default'){
  !$GLOBALS['DB'] && $GLOBALS['DB']=array();
  if(!$GLOBALS['DB'][$token]){
    $info=parse_url($GLOBALS['db'][$token]);
    $dbType='db_'.$info['scheme'];
    include_once ONEZ_ROOT.'/include/'.$dbType.'.class.php';
    $GLOBALS['DB'][$token]=new $dbType($info);
  }
  return $GLOBALS['DB'][$token];
}
function onlineip(){
	if(getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
		$onlineip = getenv('HTTP_CLIENT_IP');
	} elseif(getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
		$onlineip = getenv('HTTP_X_FORWARDED_FOR');
	} elseif(getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
		$onlineip = getenv('REMOTE_ADDR');
	} elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
		$onlineip = $_SERVER['REMOTE_ADDR'];
	}
	$onlineip = preg_replace("/^([\d\.]+).*/", "\\1", $onlineip);
	return $onlineip;
}
function showPage($token,$field='content'){
  global $PAGE;
  if(!$PAGE[$token]){
    $PAGE[$token]=D()->one('page','*',"token='$token'");
    if(!$PAGE[$token])return('记录不存在');
  }
  return $PAGE[$token][$field];
}

function ucdata($data,$touc=1){
	global $ucdbcharset;
	define('UC_DBCHARSET') && $ucdbcharset=UC_DBCHARSET;
	if(strtolower($ucdbcharset)=='gbk'){
		$data=$touc ? oiconv('utf-8','gbk',$data) : oiconv('gbk','utf-8',$data);
	}
	return $data;
}

function ero($msg1,$msg2="1"){
  if ($msg2=="0"){
    echo "<script language=\"javascript\">alert('".$msg1."');window.close();</script>";
    exit;
  }elseif($msg2=="1"){
    echo "<script language=\"javascript\">alert('".$msg1."');history.go(-1);</script>";
    exit;
  }elseif($msg2=="2"){
    echo "<script language=\"javascript\">alert('".$msg1."');</script>";
  }elseif($msg2=="3"){
    echo "<script language=\"javascript\">location.href='".$msg1."';</script>";
    exit;
  }elseif($msg2=="4"){
    echo "<script language=\"javascript\">alert('".$msg1."');</script>";
    exit();
  }else{
    echo "<script language=\"javascript\">alert('".$msg1."');top.location.href='".$msg2."';</script>";
    exit;
  } 
}
function post($url,$fields='',$options=null){
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.9.0.19) Gecko/2010031422 Firefox/3.0.19');
  curl_setopt($ch, CURLOPT_TIMEOUT, $options['timeout'] ? $options['timeout'] : 10);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch, CURLOPT_HEADER, $options['header']);
  if($options['cookie']){
    $cookieFile=cookiefile($options['cookie']);
    curl_setopt($ch, CURLOPT_COOKIEJAR, $cookieFile); //保存
    curl_setopt($ch, CURLOPT_COOKIEFILE, $cookieFile); //读取
  }
  curl_setopt($ch, CURLOPT_REFERER,$options['baseurl'] ? $options['baseurl'] : $url);
  if($fields){
    curl_setopt($ch, CURLOPT_POSTFIELDS,$fields);
    curl_setopt($ch, CURLOPT_POST,1);
  }
  $output = curl_exec($ch);
  curl_close($ch);
  return $output;
}
function cookiefile($token,$clear=false){
  $cookieFile=ONEZ_ROOT.'onezdata/cookie/'.$token.'.txt';
  if(!file_exists($cookieFile)){
  	mkdirs(dirname($cookieFile));
  	@touch($cookieFile);
  }
  if($clear){
    @unlink($cookieFile);
  }
  return $cookieFile;
}
function onez_call($funcName){
  if(function_exists($funcName)){
    return $funcName();
  }
}
function getToken($uid){
  $token=md5(StrCode($uid,'ENCODE'));
  return $token;
}
function C(&$c,$from='me'){
  $charset=strtolower(CHARSET)=='gbk' ? 'gbk' : 'utf-8';
  if($charset=='utf-8'){
    return $c;
  }
  if($from=='me'){
    $c=oiconv('utf-8',$charset,$c);
  }else{
    $c=oiconv($charset,'utf-8',$c);
  }
  return $c;
}